<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据库表管理</title>
    <style>
        body {
            font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
            margin: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        .search-bar {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
            align-items: center;
        }
        .search-bar input {
            padding: 8px 12px;
            flex-grow: 1;
            max-width: 300px;
        }
        .search-bar button {
            padding: 8px 16px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        .search-bar button:hover {
            background-color: #0056b3;
        }
        .page-size-selector {
            margin-left: auto;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        .page-size-selector select {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        table th, table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        table th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        table tr:hover {
            background-color: #f5f5f5;
        }
        .pagination {
            display: flex;
            justify-content: center;
            gap: 5px;
            margin-top: 20px;
        }
        .pagination button {
            padding: 6px 12px;
            border: 1px solid #ddd;
            background-color: white;
            cursor: pointer;
        }
        .pagination button.active {
            background-color: #007bff;
            color: white;
            border-color: #007bff;
        }
        .pagination button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        .submit-btn {
            background-color: #28a745;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        .submit-btn:hover {
            background-color: #218838;
        }
        .selected-count {
            margin: 10px 0;
            color: #666;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>数据库表列表</h1>

    <div class="search-bar">
        <input type="text" id="tableName" placeholder="请输入表名搜索">
        <button id="searchBtn">搜索</button>
        <button id="resetBtn">重置</button>

        <!-- 每页显示条数选择器 -->
        <div class="page-size-selector">
            <span>每页显示：</span>
            <select id="pageSizeSelect">
                <option value="5">5条</option>
                <option value="10">10条</option>
                <option value="20">20条</option>
                <option value="50">50条</option>
                <option value="100">100条</option>
            </select>
        </div>

    </div>

    <table>
        <thead>
        <tr>
            <th><input type="checkbox" id="selectAll"></th>
            <th>表名称</th>
            <th>表介绍</th>
            <th>创建时间</th>
        </tr>
        </thead>
        <tbody id="tableBody">
        <!-- 表格数据将通过JS动态填充 -->
        </tbody>
    </table>

    <div class="selected-count">已选择 <span id="selectedNum">0</span> 个表</div>
    <button class="submit-btn" id="submitBtn">生成代码</button>

    <div class="pagination" id="pagination">
        <!-- 分页控件将通过JS动态填充 -->
    </div>
</div>

<script src="/js/jquery-3.6.0.min.js"></script>
<script>
    // 当前页码和每页条数
    let currentPage = 1;
    let pageSize = 5;
    // 记录选中的表
    const selectedTables = new Set();

    // 页面加载完成后初始化
    $(document).ready(function() {
        loadTableData();

        // 搜索按钮点击事件
        $("#searchBtn").click(function() {
            currentPage = 1; // 重置为第一页
            loadTableData();
        });

        // 重置按钮点击事件
        $("#resetBtn").click(function() {
            $("#tableName").val("");
            $("#pageSizeSelect").val("10");
            currentPage = 1;
            loadTableData();
        });

        // 每页显示条数变化事件
        $("#pageSizeSelect").change(function() {
            pageSize = parseInt($(this).val());
            currentPage = 1; // 重置为第一页
            loadTableData();
        });

        // 全选/取消全选
        $("#selectAll").click(function() {
            const isChecked = $(this).prop("checked");
            $("input[name='tableItem']").each(function() {
                const tableName = $(this).val();
                if (isChecked) {
                    selectedTables.add(tableName);
                } else {
                    selectedTables.delete(tableName);
                }
                $(this).prop("checked", isChecked);
            });
            updateSelectedCount();
        });

        // 提交选中的表
        $("#submitBtn").click(function() {
            if (selectedTables.size === 0) {
                alert("请至少选择一个表");
                return;
            }
            const tableNames = Array.from(selectedTables);
            $.ajax({
                url: "/generator/postGeneratorCode",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify(tableNames),
                success: function(res) {
                    alert("提交成功，共提交 " + tableNames.length + " 个表, \n 下载路径为："+res);
                },
                error: function(xhr, status, error) {
                    alert("提交失败: " + error);
                }
            });
        });
    });

    // 同时检查loadTableData函数中的参数传递是否正确
    function loadTableData() {
        const tableName = $("#tableName").val().trim();

        // 显示加载状态
        $("#tableBody").html('<tr><td colspan="4" style="text-align:center;">加载中...</td></tr>');

        $.ajax({
            url: "/qry/qryTable",
            type: "POST",
            contentType: "application/json",
            // 确保参数正确传递
            data: JSON.stringify({
                pageNum: currentPage,
                pageSize: pageSize,
                tableName: tableName
            }),
            success: function(page) {
                // 检查返回的分页对象是否正确
                if (page && page.records) {
                    renderTable(page.records);
                    renderPagination(page);
                    // 清除之前的选中状态
                    selectedTables.clear();
                    $("#selectAll").prop("checked", false);
                    updateSelectedCount();
                } else {
                    console.error("返回数据格式不正确", page);
                    $("#tableBody").html('<tr><td colspan="4" style="text-align:center;">数据加载失败</td></tr>');
                }
            },
            error: function(xhr, status, error) {
                console.error("加载数据失败: " + error, xhr);
                $("#tableBody").html(`<tr><td colspan="4" style="text-align:center;">加载失败: ${error}</td></tr>`);
            }
        });
    }

    // 渲染表格数据
    function renderTable(data) {
        const tableBody = $("#tableBody");
        tableBody.empty();

        if (data.length === 0) {
            tableBody.append(`
                    <tr>
                        <td colspan="4" style="text-align: center;">没有找到匹配的数据</td>
                    </tr>
                `);
            return;
        }

        data.forEach(table => {
            const row = $(`
                    <tr>
                        <td><input type="checkbox" name="tableItem" value="${table.tableName}"></td>
                        <td>${table.tableName}</td>
                        <td>${table.tableComment || '无描述'}</td>
                        <td>${formatDate(table.createTime)}</td>
                    </tr>
                `);
            tableBody.append(row);

            // 为复选框添加点击事件
            row.find("input[name='tableItem']").click(function() {
                const tableName = $(this).val();
                if ($(this).prop("checked")) {
                    selectedTables.add(tableName);
                } else {
                    selectedTables.delete(tableName);
                }
                updateSelectedCount();
            });
        });
    }

    // 渲染分页控件 - 修复版
    function renderPagination(page) {
        const pagination = $("#pagination");
        pagination.empty();

        // 上一页按钮
        const prevBtn = $(`<button id="prevPage" ${currentPage === 1 ? 'disabled' : ''}>上一页</button>`);
        prevBtn.on('click', function() {
            if (currentPage > 1) {
                currentPage--;
                loadTableData();
            }
        });
        pagination.append(prevBtn);

        // 页码按钮
        const totalPages = page.pages;
        const visiblePages = 5; // 可见页码数量

        let startPage = Math.max(1, currentPage - Math.floor(visiblePages / 2));
        let endPage = Math.min(totalPages, startPage + visiblePages - 1);

        // 调整起始页，确保显示足够的页码
        if (endPage - startPage + 1 < visiblePages) {
            startPage = Math.max(1, endPage - visiblePages + 1);
        }

        // 第一页按钮
        if (startPage > 1) {
            const firstBtn = $(`<button data-page="1">1</button>`);
            firstBtn.on('click', function() {
                currentPage = 1;
                loadTableData();
            });
            pagination.append(firstBtn);

            if (startPage > 2) {
                pagination.append(`<span>...</span>`);
            }
        }

        // 中间页码
        for (let i = startPage; i <= endPage; i++) {
            const pageBtn = $(`<button data-page="${i}" ${i === currentPage ? 'class="active"' : ''}>${i}</button>`);
            pageBtn.on('click', function() {
                currentPage = parseInt($(this).data("page"));
                loadTableData();
            });
            pagination.append(pageBtn);
        }

        // 最后一页按钮
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                pagination.append(`<span>...</span>`);
            }

            const lastBtn = $(`<button data-page="${totalPages}">${totalPages}</button>`);
            lastBtn.on('click', function() {
                currentPage = totalPages;
                loadTableData();
            });
            pagination.append(lastBtn);
        }

        // 下一页按钮
        const nextBtn = $(`<button id="nextPage" ${currentPage >= totalPages ? 'disabled' : ''}>下一页</button>`);
        nextBtn.on('click', function() {
            if (currentPage < totalPages) {
                currentPage++;
                loadTableData();
            }
        });
        pagination.append(nextBtn);

        // 显示当前页和总页数
        pagination.append(`<span style="margin-left: 10px;">第 ${currentPage}/${totalPages} 页，共 ${page.total} 条记录</span>`);
    }

    // 更新选中数量
    function updateSelectedCount() {
        $("#selectedNum").text(selectedTables.size);
    }

    // 格式化日期
    function formatDate(dateString) {
        if (!dateString) return "";
        const date = new Date(dateString);
        return date.toLocaleString();
    }
</script>
</body>
</html>
